<template>
    <div>
        <!-- 查询表单 -->
        <a-card :bordered="false">
            <a-form :model="searchForm" layout="inline" @finish="handleSearch">
                <a-form-item label="标题" name="title">
                    <a-input v-model:value="searchForm.title" placeholder="请输入标题关键词" allow-clear />
                </a-form-item>

                <a-form-item label="是否置顶" name="isPinned">
                    <a-select v-model:value="searchForm.isPinned" placeholder="请选择" allow-clear style="width: 120px">
                        <a-select-option :value="true">是</a-select-option>
                        <a-select-option :value="false">否</a-select-option>
                    </a-select>
                </a-form-item>

                <a-form-item>
                    <a-space>
                        <a-button type="primary" html-type="submit">查询</a-button>
                        <a-button @click="handleReset">重置</a-button>
                    </a-space>
                </a-form-item>
            </a-form>
        </a-card>
        <!-- 表格 -->
        <a-card :bordered="false" class="mt-4">
            <a-table
                :columns="columns"
                :data-source="dataSource"
                :pagination="pagination"
                :loading="loading"
                @change="handleTableChange"
            >
                <template #bodyCell="{ column, record }">
                    <template v-if="column.dataIndex === 'isPinned'">
                        <a-tag v-if="record.isPinned" color="green">是</a-tag>
                        <a-tag v-else>否</a-tag>
                    </template>
                    <!-- 操作列 -->
                    <template v-if="column.dataIndex === 'action'">
                        <a-space :size="8">
                            <a-button type="link" size="small" @click="handleEdit(record)"> 编辑 </a-button>
                            <a-button type="link" size="small" @click="handleView(record)"> 查看 </a-button>
                            <a-popconfirm
                                title="确定要删除吗？"
                                ok-text="确定"
                                cancel-text="取消"
                                @confirm="handleDelete(record)"
                            >
                                <a-button type="link" size="small" danger>删除</a-button>
                            </a-popconfirm>
                        </a-space>
                    </template>
                </template>
            </a-table>
        </a-card>
    </div>
</template>
<script lang="ts" setup>
import { usePagination } from "alova/client";
import { message, type TableProps } from "ant-design-vue";

import { DateTimeUtils } from "@/utils/DateTimeUtils";

const searchForm = reactive({
    title: "",
    isPinned: undefined as boolean | undefined
});

const handleSearch = async () => {
    // 改变page时（翻页或跳页），会自动触发请求
    // page.value = 1;
    console.log("searchForm", searchForm);
    await send(searchForm);
    Object.keys(searchForm).forEach(key => {
        // @ts-ignore
        searchForm[key] = "";
    });
};
const handleReset = () => {
    Object.keys(searchForm).forEach(key => {
        // @ts-ignore
        searchForm[key] = "";
    });
    // send({});
    nextTick(() => {
        page.value = 1;
    });
};

// 列表列
const columns: TableProps["columns"] = [
    {
        title: "序号",
        dataIndex: "index",
        key: "index", // 列的key，默认为dataIndex
        customRender: row => {
            // 连续序号 = (当前页码 - 1) * 每页条数 + 当前行索引 + 1
            return (page.value - 1) * pageSize.value + row.index + 1;
        },
        width: 80,
        align: "center"
    },
    {
        title: "内容",
        dataIndex: "title"
    },
    {
        title: "热度值",
        dataIndex: "hotScore",
        width: "20%"
    },
    {
        title: "置顶",
        dataIndex: "isPinned"
    },
    {
        title: "创建时间",
        dataIndex: "createdAt",
        key: "createdAt",
        customRender: row => DateTimeUtils.formatDateTime(row.record.createdAt),
        width: 180
    },
    {
        title: "操作",
        dataIndex: "action",
        key: "action",
        width: 200,
        fixed: "right",
        align: "center"
    }
];

const {
    // 加载状态
    loading,
    // 列表数据
    data: dataSource,
    // 是否为最后一页
    // 下拉加载时可通过此参数判断是否还需要加载
    isLastPage,
    // 当前页码，改变此页码将自动触发请求
    page,
    // 每页数据条数
    pageSize,
    // 分页页数
    pageCount,
    // 总数据量
    total,
    send
} = usePagination(
    // Method实例获取函数，它将接收page和pageSize，并返回一个Method实例
    (page, pageSize, searchForm) => {
        console.log("...searchForm", searchForm);
        return Apis.Hotlist.page({ params: { current: page, size: pageSize, ...searchForm } });
    },
    {
        // 从响应数据中提取数据
        total: res => res.data.total,
        data: res => res.data.list,
        // 设置请求未完成时，data和total的初始值，避免template中出现 undefined.xxx 调用错误
        initialData: { total: 0, data: [] },
        initialPage: 1, // 初始页码，默认为1
        initialPageSize: 10 // 初始每页数据条数，默认为10
    }
);

const pagination = computed<TableProps["pagination"]>(() => ({
    showSizeChanger: true,
    defaultPageSize: 10,
    // showTotal: (total, range) => `共 ${total} 条数据`,
    showQuickJumper: true,
    showTotal: (total: number, range: [number, number]) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
    showLessItems: true,
    total: total.value,
    current: page.value,
    pageSize: pageSize.value
}));

// 	分页、排序、筛选变化时触发
const handleTableChange: TableProps["onChange"] = (pag, _filters, _sorter) => {
    const { current, pageSize: size } = pag;
    page.value = current ?? 1;
    pageSize.value = size ?? 10;
    // 延迟更新，防止alova内部的响应式断裂
    // nextTick(() => {
    //     // 改变page时（翻页或跳页），会自动触发请求
    //     if (current && current !== page.value) page.value = current;
    //     // 改变pageSize时（每页数据条数改变），会自动触发请求
    //     if (size && size !== pageSize.value) {
    //         pageSize.value = size;
    //         page.value = 1; // 切换每页数据条数时，跳转到第一页
    //     }
    // });
};

const handleEdit = record => {
    message.info(`编辑: ${record.name}`);
    console.log("编辑记录:", record);
};

const handleView = record => {
    message.info(`查看: ${record.name}`);
};

const handleDelete = record => {
    message.warning(`删除: ${record.name}`);
};
</script>
